import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/model/consult.dart';
import 'package:leader_doctor_flutter/router/router.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../common/data/app.dart';
import '../../../common/http/api.dart';
import '../../../common/http/http_client.dart';
import '../../../common/utils/consultation_utils.dart';
import '../../../common/utils/user_utils.dart';
import '../../../common/widget/comm_widget.dart';
import '../../../styles/colors.dart';

/// @Author lixiaobin
/// @Date 2024/2/21
/// @Description 咨询记录
class ConsultationRecordPage extends StatefulWidget {
  const ConsultationRecordPage({super.key});

  @override
  State<ConsultationRecordPage> createState() => _ConsultationRecordPageState();
}

class _ConsultationRecordPageState extends State<ConsultationRecordPage> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final _tabArr = [
    {'title': '全部', 'status': '-1'},
    {'title': '未接诊', 'status': '-2'},
    {'title': '已结束', 'status': '2'}
  ];
  final _consultList = <ConsultModel>[];
  var _pageNo = 1;
  var _status = '-1';
  final _pageSize = 20;
  final _refreshController = RefreshController(initialRefresh: false);

  void _onRefresh() async {
    _pageNo = 1;
    _findConsultList();
  }

  void _onLoading() async {
    _pageNo++;
    _findConsultList();
  }

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _tabArr.length, vsync: this);
    _onRefresh();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: CommWidget.getCommAppbar(context),
        body: Container(
            color: ColorRes.colorf9f9fa,
            child: Column(
              children: [_buildTaberView(), _buildListView()],
            )));
  }

  /// tab view
  Widget _buildTaberView() {
    return Container(
        color: ColorRes.white,
        child: TabBar(
          controller: _tabController,
          onTap: (int index) {
            _status = _tabArr[index]['status'] ?? '';
            _onRefresh();
          },
          indicatorColor: ColorRes.colorMain,
          labelColor: ColorRes.colorMain,
          unselectedLabelColor: ColorRes.color333333,
          indicatorSize: TabBarIndicatorSize.label,
          tabs: _tabArr.map((e) => Tab(text: e['title'])).toList(),
        ));
  }

  Widget _buildListView() {
    return Expanded(child: _buildSmartRefresher());
  }

  /// 刷新组件
  Widget _buildSmartRefresher() {
    return SmartRefresher(
        controller: _refreshController,
        enablePullDown: true,
        enablePullUp: true,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: _consultList.isEmpty
            ? CommWidget.buildEmptyView()
            : ListView.builder(
                shrinkWrap: true,
                itemBuilder: (c, i) => _buildItem(c, i),
                itemCount: _consultList.length,
              ));
  }

  /// item
  Widget _buildItem(BuildContext c, int i) {
    var item = _consultList[i];
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          context.push('${PageUrl.consultationDetail}?id=${item.id}', extra: item);
        },
        child: Container(
          color: ColorRes.white,
          padding: EdgeInsets.only(left: 12.w, right: 12.w, top: 15.w),
          margin: EdgeInsets.only(top: 15.w),
          child: Column(
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  ClipRRect(
                      borderRadius: BorderRadius.circular(20.w),
                      child: ImageLoader.loadPatientAvatar(item.patientHeadIcon,
                          sex: item.patientSex, size: Size(40.w, 40.w))),
                  SizedBox(width: 12.w),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        ConsultModel.getPatientName(item),
                        style: TextStyle(
                          color: ColorRes.color333333,
                          fontSize: 16.sp,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Text(
                        UserUtils.getSexAndAge(item.patientSex, item.patientAge),
                        style: TextStyle(
                          color: ColorRes.color666666,
                          fontSize: 15.sp,
                        ),
                      )
                    ],
                  ),
                  SizedBox(height: 24.w),
                  Text(
                    ConsultationUtils.getType(item.type),
                    style: TextStyle(
                      color: ColorRes.colorffb50c,
                      fontSize: 13.sp,
                    ),
                  ),
                  SizedBox(width: 15.w),
                  CommWidget.buildConsultTypeBtn('义诊', isShow: item.promotionChannel == '4'),
                  Expanded(
                      child: Container(
                    margin: EdgeInsets.only(top: 12.w),
                    alignment: Alignment.centerRight,
                    child: ImageLoader.loadAsset('grey_setup.webp', 12.w),
                  )),
                ],
              ),
              SizedBox(height: 10.w),
              CommWidget.buildLine(),
              SizedBox(height: 10.w),
              Row(
                children: [
                  Text(
                    ConsultationUtils.getStatus(item),
                    style: TextStyle(
                      color: ColorRes.color666666,
                      fontSize: 14.sp,
                    ),
                  ),
                  Text(
                    _getResult(item),
                    style: TextStyle(
                      color: ColorRes.color999999,
                      fontSize: 14.sp,
                    ),
                  ),
                  Visibility(
                      visible: '1' == item.refund,
                      child: Container(
                          margin: EdgeInsets.only(left: 10.w),
                          child: ImageLoader.loadAsset('icon_consult_refund.webp', 20.w))),
                  Expanded(
                      child: Text(
                    item.orderTime ?? '',
                    textAlign: TextAlign.end,
                    style: TextStyle(
                      color: ColorRes.color999999,
                      fontSize: 12.sp,
                    ),
                  )),
                ],
              ),
              SizedBox(height: 10.w),
            ],
          ),
        ));
  }

  /// 原因
  String _getResult(ConsultModel item) {
    var result = item.endFeedback;
    switch (item.status ?? '') {
      case '4':
      case '6':
        result = item.refuseConsult;
        break;
      default:
        break;
    }
    return result == null ? '' : '-$result';
  }

  /// 查询患者咨询
  _findConsultList() async {
    var user = App.instance.userInfo;
    var response = await HttpClient.post(HttpRequest(Api.findConsultListNew, urlParams: {
      'doctorUserId': user?.id ?? '',
      'status': _status,
      'pageIndex': _pageNo,
      'pageSize': _pageSize,
    }));
    var serviceResult = ServiceResult<List<ConsultModel>>.list(
        response, (map) => (map ?? []).map((e) => ConsultModel.fromJson(e)).toList());

    if (serviceResult.success) {
      var list = serviceResult.responseBody ?? [];
      if (_pageNo == 1) {
        _consultList.clear();
      }
      _consultList.addAll(list);
    }

    _refreshController.refreshCompleted();
    _refreshController.loadComplete();
    setState(() {});
  }
}
